const net = require('net');
const http = require('./http.js');

var tcp_server = net.createServer();  // 创建 tcp server

var Sockets = {};
var SocketID = 1;

// 监听 端口
tcp_server.listen(80, '0.0.0.0', function (){
    console.log('http_server listening 80');
});

// 处理客户端连接
tcp_server.on('connection',function (socket){
    Sockets[SocketID] =socket;
    SocketID++;
    DealConnect(socket);
})

tcp_server.on('error', function (){
    console.log('tcp_server error!1');
})

tcp_server.on('close', function () {
    console.log('tcp_server close!2');
})
function broadcast(data){
    // 向所有客户端广播消息
    for(var i in Sockets){
        Sockets[i].write(data);
    }
}

// 处理每个客户端消息
function DealConnect(socket){
    socket.on('data',function(data){
        data = data.toString();
        let data_arr = data.split('\r\n');
        let entity = new http(socket);
        entity.Enter(data_arr);        
    })


    /**
     * 监听客户端的各种断开
     * TODO http正在处理中, 客户端断开连接
     */

    // 客户端正常断开时执行
    socket.on('close', function () {
        if(socket.state != 3) console.log('client unusual disconneted!');
        
    })


    // 客户端正异断开时执行
    socket.on("error", function () {
        console.log('client error disconneted!');
    });
}